﻿using Cinemachine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class Play : MonoBehaviour
{
    public string GateName = "Scenes/Level/";
    [Header("Ui按钮控制")]
    public bool UiButton;

    [Header("移动设置")]
    //移动速度
    public float Speed;
    //跳跃力
    public float Jumping;
    //跳跃间隔时间
    public float JumpingTime;
    //摄像机控制
    public GameObject Camera;
    //最大连跳数
    public int MaxEvenJumpNumber;
    [Header("受伤设定")]
    //伤害动画持续时间
    public float HurtTime;
    //受伤弹开的距离
    public float DamageAway;
    //受伤无敌的时间
    public float DamageInvincibleTime;
    [Header("UI控件绑定")]
    //死亡显示
    public GameObject GameOver;
    //血量显示
    public GameObject BloodVolume;
    [Header("游戏数据")]
    //游戏数据
    public GameObject GaemData;
    [Header("检测设置")]
    //碰撞器
    public Collider2D Coll;
    //触发器
    public Collider2D Trigger;
    //层（特殊）
    public LayerMask Special;
    //层（地面）
    public LayerMask Ground;
    //层（敌人）
    public int Enemy;
    //层（收集物）
    public int Pickup;
    //层（掉落）
    public int Drop;
    //销毁
    public GameObject DestroyEnemy;
    //收集
    public GameObject CollectPickup;
    //复活点
    public Vector3 ResurrectionPoint;
    [System.Serializable]
    public class State_info
    {
        //连跳数
        public int Jumps_Number;
        //最后受伤时间
        public float IastHurtTime;
        //最后跳跃的时间
        public float IastJumpingTime;
        //无敌
        public bool Invincible;
        //是否死亡
        public bool Death;
        //是否可以消灭敌人
        public bool EliminateEnemy;
        //上下跳跃按钮
        public bool Left, Right, Top;
        //掉落
        public bool Drop;

    }
    [Header("状态")]
    public State_info State;

    private Rigidbody2D rb;
    private Animator animator;

    void Start()
    {
        //绑定游戏数据
        GaemData = this.gameObject;
        //绑定游戏Rigidbody
        rb = GetComponent<Rigidbody2D>();
        //绑定游戏Animator
        animator = GetComponent<Animator>();
        //绑定初始位置
        ResurrectionPoint = transform.position;
        /// 初 始 化
        //生命
        GaemData.GetComponent<GameData>().LevelGame.Life = 1;
        BloodVolume.GetComponent<Text>().text = "X" + GaemData.GetComponent<GameData>().LevelGame.Life;
        //播放
        Time.timeScale = 1f;

    }

    void Update()
    {
        //跳跃
        Jump();
        //时间控制
        TimeJudge();
        //碰撞检测

    }

    void FixedUpdate()
    {
        //移动
        Move();
    }

    //移动
    void Move()
    {
        //设置左右移动
        float Horizontal;
        //判断是否触屏控制
        if (UiButton)
        {
            Horizontal = 0;
            if (State.Left && !State.Right)
            {
                Horizontal = -1;
            }
            if (State.Right && !State.Left)
            {
                Horizontal = 1;
            }
            if(State.Left && State.Right)
            {
                Horizontal = 0;
            }
        }
        else
        {
            Horizontal = Input.GetAxisRaw("Horizontal");
        }

        if(Horizontal > 0)
        {
            animator.SetBool("Run", true);
            transform.localScale = new Vector2(1, transform.localScale.y);
        }
        if(Horizontal < 0)
        {
            animator.SetBool("Run", true);
            transform.localScale = new Vector2(-1, transform.localScale.y);
        }
        if(Horizontal == 0)
        {
            animator.SetBool("Run", false);
        }
        rb.velocity = new Vector2(Speed * Horizontal, rb.velocity.y);
    }
    
    //跳跃
    void Jump()
    {
        if (Coll.IsTouchingLayers(Ground) || Coll.IsTouchingLayers(Special))
        {
            if(Time.time - State.IastJumpingTime > JumpingTime) { 
                State.Jumps_Number = 0;
                animator.SetInteger("Jump", 0);
                State.EliminateEnemy = false;
            }
        }
        bool Jump;
        if (UiButton)
        {
            Jump = State.Top;
            if (State.Top)
            {
                State.Top = false;
            }
        }
        else
        {
            Jump = Input.GetKeyDown(KeyCode.W);
        }
        if (Jump) {
            if (Coll.IsTouchingLayers(Ground) || State.Jumps_Number < MaxEvenJumpNumber)
            {
                State.Jumps_Number++;
                animator.SetInteger("Jump", 1);
                rb.velocity = new Vector2(rb.velocity.x, Jumping);
                State.IastJumpingTime = Time.time;
            }
        }
        if (rb.velocity.y < 0 && !Coll.IsTouchingLayers(Ground) && !Trigger.IsTouchingLayers(Ground))
        {
            animator.SetInteger("Jump", 2);
            State.EliminateEnemy = true;
        }

    }

    //时间判断
    void TimeJudge()
    {
        if (State.Invincible)
        {
            if(Time.time - State.IastHurtTime > DamageInvincibleTime)
            {
                State.Invincible = false;
                Coll.enabled = true;
                Trigger.enabled = true;
                animator.SetBool("Hurt", false);
                //Rigidbody.constraints = RigidbodyConstraints2D.FreezeRotation;
            }
        }
        if (State.Death)
        {
            Resurrection();
        }
        if(Time.time - State.IastHurtTime > HurtTime)
        {
            animator.SetBool("Hurt", false);
        }
    }

    //死亡
    public void Death()
    {
        GaemData.GetComponent<GameData>().LevelGame.Life--;
        if(GaemData.GetComponent<GameData>().LevelGame.Life != 0 && !State.Drop)
        {
            Trigger.enabled = false;
            BloodVolume.GetComponent<Text>().text = "X" + GaemData.GetComponent<GameData>().LevelGame.Life.ToString();
            State.IastHurtTime = Time.time;
            State.Invincible = true;
            animator.SetBool("Hurt", true);
            transform.position = new Vector2((-transform.localScale.x * DamageAway) + transform.position.x, transform.position.y);
        }
        else
        {
            Camera.GetComponent<CinemachineVirtualCamera>().Follow = transform.parent;
            GameOver.SetActive(true);
            Coll.enabled = false;
            Trigger.enabled = false;
            //animator.SetBool("Hurt", true);
            State.IastHurtTime = Time.time;
            State.Death = true;
            State.Drop = false;
        }
    }
    //死亡复活
    void Resurrection()
    {
        if (State.Death)
        {
            if(Time.time - State.IastHurtTime > HurtTime)
            {
                SceneManager.LoadScene(GateName);
            }
        }
    }
    //消灭
    void Eliminate(GameObject game)
    {
        Vector3 position = game.transform.position;
        Destroy(game);
        GameObject boom = Instantiate(DestroyEnemy);
        boom.transform.position = position;
    }

    //收集
    void Collect(GameObject game)
    {
        Vector3 position = game.transform.position;
        Destroy(game);
        GameObject boom = Instantiate(CollectPickup);
        boom.transform.position = position;
    }
    
    void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.layer == Drop)
        {
            State.Drop = true;
            Death();
        }
    }

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.layer == Enemy && !State.Invincible)
        {
            Eliminate(collision.gameObject);
        }
        if (collision.gameObject.layer == Pickup && !State.Invincible)
        {
            Collect(collision.gameObject);
        }
    }

    void OnCollisionStay2D(Collision2D collision)
    {
        if (collision.gameObject.layer == Enemy && !State.Invincible)
        {
            Death();
        }
    }

}
